##################################
# Figures for Ambguity Model Estimates 


require(ggplot2)
require(reshape2)


# This script provides functions to create figures for the model estimates
# a) Country specific
# b) Combined figure
# c) Comparsion with other mesaruments

## a) Country specific
###########

### Distribution of observations

  # Creates figure of observed expert placments for country-year
  
  ggplot_distribution_experts <- function(data=chc, c="ger", y="2006", 
                                          polnam=issue_names ){
    
    # Subset Data and get Party Names
    sd <- data[data$ctry_name==c & data$year==y,]
    parties <- unique(sd$pid_nam)
      
    # Select Items
    Item <- sd[,c("pid",paste("pos.",c(1:3,5:10,13,16),sep=""))]
    
    # Change from wide to long format
    df <- melt(Item,"pid")
    
    # Create Factors for parties and issue items
    df$pid <- as.factor(df$pid)
    levels(df$pid) <-  parties
    df$variable <- as.factor(df$variable)
    levels(df$variable) <- polnam
    
    # Call GGplot on Data
    ggplot(na.omit(df), aes(x=value)) + geom_bar() +
      facet_grid(variable ~ pid)  + 
      ylab("") + xlab("")+
      scale_y_discrete(breaks=c(0,4,8)) +
      scale_x_discrete(limits=c(0:10),labels=c("0",rep("",9),"10"),expand=c(0.05,0.05)) + 
      theme_bw() +
      theme(
        text=element_text(family="Palatino", size=11)
        ,strip.text.y = element_text(angle=360)) +   
      scale_fill_grey() 
    
  }
  


### Party Estimates
  
  # Creates figure of party estimates 
  
  ggplot_party_est <- function(data = res, c= "ger"
                                     ,polnam=issue_names ){
    
    # Subset Data; Create Factors
    df_est <- res[res$ctry_nam==c,]
    names(df_est)[grep("%",names(df_est))] <- c("vvlow","vlow","low","mid","high","vhigh","vvhigh")
    df_est$pid_nam <- as.factor(df_est$pid_nam)
    df_est$type <- as.factor(ifelse(df_est$par%in%paste("x[",1:20,"]",sep=""),"Platform","Ambguity") )
    
    # Plot using ggplot
    ggplot(df_est) +  facet_grid(pid_nam ~ type, scales="free_x") + 
      geom_segment(aes(x=vlow,xend=vhigh,y=year,yend=year),
                   size=0.8,alpha=0.8) +
      geom_segment(aes(x=low,xend=high,y=year,yend=year),
                   size=1.5) +
      geom_point(aes(x=mean,y=year),
                 size=2) +
      xlab("Estimates") + ylab("") + 
      theme(panel.grid.major = element_blank(),
            panel.grid.minor = element_blank(),
            legend.position = "top"
            ,text=element_text(family="Palatino", size=11)
            , strip.text.y = element_text(size=11,angle=360)
      ) +   scale_colour_grey() + 
      theme_bw()
    
  }

    
  
### Item Estimates
  
  # Creates figure of item paramters 
  
  ggplot_item_est <- function(data = items, c= "ger"
                              ,polnam=issue_names){
  
    # Subset and anipulate data
    di <- items[items$ctry_nam==c,]
    names(di)[grep("%",names(di))] <- c("vvlow","vlow","low","mid","high","vhigh","vvhigh")
    s1 <- grep("[a-b]{1}k\\[[0-9]+\\]",di$par)
    di <- di[s1,]
    di$type <- as.factor(ifelse(di$par%in%paste("ak[",1:11,"]",sep=""),"Difficulty","Discrimination") )
    di$issue <- as.factor(1:11)
    levels(di$issue) <- issue_names
    
    # Call Ggplot
    ggplot(di) +  facet_grid(issue ~ type, scales="free_x") + 
      geom_segment(aes(x=vlow,xend=vhigh,y=year,yend=year,group=issue),
                   size=0.8,alpha=0.8) +
      geom_segment(aes(x=low,xend=high,y=year,yend=year,group=issue),
                   size=1.5) +
      geom_point(aes(x=mean,y=year,group=issue),
                 size=2) +
      xlab("Estimates") + ylab("") + 
      #scale_y_continuous(limits=c(min(df$low),max(df$high)))+
      theme(panel.grid.major = element_blank(),
            panel.grid.minor = element_blank(),
            #panel.background = element_blank(),
            legend.position = "top"
            ,text=element_text(family="Palatino", size=11)
            , strip.text.y = element_text(size=11,angle=360)
      ) +   scale_colour_grey() + 
      theme_bw()

  }
  

####################    
## b) Combined Graphs

  
ggplot_cob_est <- function(data = res, grep_par="nu", y = 2014){
  
  res_nu <- data[grep(grep_par,data$par),]
  names(res_nu)[grep("%",names(res_nu))] <- c("vvlow","vlow","low","mid","high","vhigh","vvhigh")
  
  ggplot(res_nu[res_nu$year%in%y,]) +  facet_wrap(~ ctry_nam, scales="free_y") + 
    geom_segment(aes(x=vlow,xend=vhigh,y=pid_nam,yend=pid_nam,col=year),
                 size=0.8) +
    geom_point(aes(x=mean,y=pid_nam,col=year),
               size=1.2) +
    xlab("Estimates") + ylab("") + 
    #scale_y_continuous(limits=c(min(df$low),max(df$high)))+
    theme(panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          #panel.background = element_blank(),
          legend.position = "top"
          ,text=element_text(family="Palatino", size=10)
    ) +   scale_colour_grey() + 
    theme_bw()
  
}

##########################
# c) Comparsion with othe rmeasurments



### Aggreagted Pattern

ggplot_alternative_d <- function(dr = res, dam = alternativmasse, grep_par="nu", 
                                 sel_am = c("sd_lr","agreement","rozans_mean","avg_sd")){
                                   
  require(GGally)
    
  res <- dr[grep(grep_par,dr$par),]
  names(res)[grep("%",names(res))] <- c("vvlow","vlow","low","mid","high","vhigh","vvhigh")
                                   
  mts <- merge(dam,res)
                                   
  sel <- c("mean",sel_am)
  mts <- as.data.frame(apply(mts[,sel],2,as.numeric))
                                   
  ggpairs(na.omit(mts), 
      upper = list(continuous = wrap("cor", size = 5)), 
      lower = list(continuous = "smooth")
      , axisLabels='show', 
      columnLabels=c("Ambguity est.","S.D. Left-Right","Agre. Left-Right","Rozenas Est.","Mean S.D.")
      ) +theme_bw() +
      theme(#panel.grid.major = element_blank(),
      #panel.grid.minor = element_blank(),
      panel.background = element_blank()
      ,text=element_text(size=10)
      )
  }

## Country-by-country


ggplot_alt_corr_ctry <- function(dr = res, dam = alternativmasse, grep_par="nu", 
                                 sel_comp = c("avg_sd"), cov_title="Average S.D. Issues Placements"){
  
  res <- dr[grep(grep_par,dr$par),]
  names(res)[grep("%",names(res))] <- c("vvlow","vlow","low","mid","high","vhigh","vvhigh")
    
  mts <- merge(dam,res)
  

  ggplot(mts,aes(x=mean,y=mts[,sel_comp])) + 
    facet_wrap( year ~ctry_nam ) +stat_smooth(method="lm",se=FALSE,alpha=0.4) +
    geom_point() + 
    xlab("Ambguity estimates") + ylab(cov_title) + 
    #scale_y_continuous(limits=c(min(df$low),max(df$high)))+
    theme(panel.grid.major = element_blank(),
          panel.grid.minor = element_blank(),
          #panel.background = element_blank(),
          legend.position = "top"
          ,text=element_text(family="Palatino", size=10)
    ) +   scale_colour_grey()

}

